#ifdef USE_SQL
#include <string.h>

#include "lib.h"
#include "rdserv.h"
#include "rdconn.h"
#include "rdhand.h"
#include "rdsql.h"
#include "rdsaved.h"
#include "rdgame.h"
#include "reddogproto.h"
#include "stdncerr.h"
#include "opts.h"
#include "log.h"
#include "badpacketmsgs.h"
#include "XMLTranslator.h"

static RedDogSQL* tracker = (RedDogSQL*)0;

typedef struct _info
{
	String		    login;
	PID				pid;
	SESSIONID		sessionId;
	RedDogGameID	gid;
	bool8			forMoney;
} Info, *pInfo;

void
RedDogServer::startTracker()
{
	ServerOpts::load();

	tracker = new RedDogSQL(ServerOpts::dbdsn,
		ServerOpts::dblogin, ServerOpts::dbpasswd);

	// CSN-8891
	webServiceCall = new WebServiceCall();
}

void
RedDogServer::stopTracker()
{
	delete tracker;
	tracker = 0;

	delete webServiceCall;
	webServiceCall = 0;
}

bool8
RedDogServer::initSuccess()
{
	if (tracker && tracker->initOK())
		return Server::initSuccess();
	else
	{
		Log::msgError("Failed to connect to the database.  Aborting.");
		return false;
	}
}

bool8
RedDogConnection::parseCasinoLogin(int32 stdReq, int32* Err)
{
	Info* info;
	int32 i;

	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[1],msgbuf[2],msgbuf[3],msgbuf[4]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;
	
	char login[PIDLEN + 1];
	memcpy(login, msgbuf + i, PIDLEN);
	login[PIDLEN] = '\0';
	i += PIDLEN;

	strlwr(login);
	info->login = login;

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{		
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
		
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
	}

	if (tracker)
	{
		int32 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}

	info->pid = info->login;

	#ifdef FORCEDSHOE       //RPF 20100317 When forcing the shue now filter by pid
	m_pid = info->login;
    #endif

	/*
	if (tracker)
	{
		int32 result = RedDogSQL::ExecFailed;

		tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		tracker->unlock();

		if (result != RedDogSQL::NoError)
		{
			if(result == RedDogSQL::AdminLogout)
				*Err = LOGINERR_ADMINLOGOUT;
			else if(result == RedDogSQL::AutoLogout)
				*Err = LOGINERR_AUTOLOGOUT;
			else
				*Err = LOGINERR_NOTLOGGEDIN;

            DEBUGMSG(("Login: attempt to play without logging in: %S",
					(const uint16*) info->login));
            delete info;
            return false;
		}
	}
	*/

	memset(info->gid, 0xff, sizeof(RedDogGameID));

	casinoSpecific = info;

	return true;
}

bool8
RedDogConnection::parseUnicodeCasinoLogin(int32 stdReq, int32* Err)
{
	Info* info;
	int32 i;

	if (msgbuf[2]	!= APP1				|| msgbuf[3] != APP2 ||
		msgbuf[4]	!= PROTO_VERSION1	|| msgbuf[5] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[1],msgbuf[2],msgbuf[3],msgbuf[4]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;

	i += info->login.deserialize(msgbuf + i);
	info->login.toLower();

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{		
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
		
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
	}

	if (tracker)
	{
		int32 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			return false;
		}
	}

	info->pid = info->login;

	#ifdef FORCEDSHOE       //RPF 20100317 When forcing the shue now filter by pid
	m_pid = info->login;
    #endif

	/*
	if (tracker)
	{
		int32 result = RedDogSQL::ExecFailed;

		tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		tracker->unlock();

		if (result != RedDogSQL::NoError)
		{
			if(result == RedDogSQL::AdminLogout)
				*Err = LOGINERR_ADMINLOGOUT;
			else if(result == RedDogSQL::AutoLogout)
				*Err = LOGINERR_AUTOLOGOUT;
			else
				*Err = LOGINERR_NOTLOGGEDIN;

            DEBUGMSG(("Login: attempt to play without logging in: %S",
					(const uint16*) info->login));
            delete info;
            return false;
		}
	}
	*/

	memset(info->gid, 0xff, sizeof(RedDogGameID));

	casinoSpecific = info;

	return true;
}

void
RedDogConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
RedDogConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
RedDogConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

bool8
RedDogConnection::trackGetBalance( int32 *balance )
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;
	int32 comp;
	*balance = 0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getBalance(ServerOpts::casinoId,
			info->pid, info->forMoney, balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == RedDogSQL::NoError);
}

int32
RedDogConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;
	int32 bal=0, comp=0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->adjustBalance(ServerOpts::casinoId,
			info->pid, info->forMoney,
			Amount, &bal, &comp);
		tracker->unlock();
	}

	if (result == RedDogSQL::NoError)
		return bal;
	return 0;
}

bool8
RedDogConnection::trackGetPlayerLimits(int32* minBet, int32* maxBet,
	int32* compFactor)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getPlayerLimits(info->pid, GAMEID, MACHID,
			minBet, maxBet, compFactor);
		tracker->unlock();
	}

	return (bool8)(result == RedDogSQL::NoError);
}

bool8
RedDogConnection::trackNewGame(int32 Bet, int32 *Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->createGame(ServerOpts::casinoId,
			info->pid, info->forMoney, info->sessionId,
			info->forMoney ? compFactor : 0,
			info->gid, Bet, Balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == RedDogSQL::NoError);
}


bool8
RedDogConnection::trackDeal(RedDogHand* Player, uint8 End, int32 Outcome,
	int32 BalAdjust, int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->deal(ServerOpts::casinoId,
			info->pid, info->forMoney, info->gid,
			Player->getCount(), Player->getCards(), End, Outcome,
			BalAdjust, Balance, &comp);
		tracker->unlock();
	}
	return (bool8)(result == RedDogSQL::NoError);
}

bool8
RedDogConnection::trackGameDone(uint8 ThirdCard, bool8 Raised, int32 outcome,
	int32 BalAdjust, int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->gameDone(ServerOpts::casinoId,
			info->pid, info->forMoney, info->gid,
			ThirdCard, Raised, outcome, BalAdjust, Balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == RedDogSQL::NoError);
}

bool8
RedDogConnection::trackHasSavedGame(int32* err)
{
	ASSERT(game == (RedDogGame*)0);

	pInfo info = (pInfo)casinoSpecific;
	RedDogSavedGame sg;
	int32 result = RedDogSQL::ExecFailed;
	bool8 exists;

	if (tracker && info)
	{
		tracker->lock();

		result = tracker->hasSavedGame(info->pid, info->forMoney,
			info->gid, &sg, &exists);

		if (result == RedDogSQL::NoError && exists)
		{
			game = new RedDogGame(this, &sg);
			if (game)
			{
				tracker->unlock();
				return true;
			}
			tracker->unlock();

			*err = LOGINERR_CONTACTCUSTSERVICE;
			return false;
		}
		else
		{
			memset(info->gid, 0xff, sizeof(RedDogGameID));

			if (RedDogSQL::NoError == result)
			{
				tracker->unlock();

				*err = 0;
				return false;			// all ok, no saved game
			}
		}

		tracker->unlock();
	}
	*err = LOGINERR_CONTACTCUSTSERVICE;
	return false;
}


bool8
RedDogConnection::trackRemoveSavedGame()
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = RedDogSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->removeSavedGame(info->gid);
		tracker->unlock();

		return (bool8)(result == RedDogSQL::NoError);
	}
	return false;
}

bool8
RedDogConnection::trackSaveGame()
{
	pInfo info = (pInfo)casinoSpecific;
	RedDogSavedGame sg;
	int32 result = RedDogSQL::ExecFailed;

	if (!game)
		return true;

	if (tracker && info)
	{
		game->save(&sg);

		tracker->lock();
		result = tracker->saveGame(info->pid, info->forMoney, info->gid, &sg);
		tracker->unlock();

		return (bool8)(result == RedDogSQL::NoError);
	}
	return false;
}

void
RedDogConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen)
{
	pInfo info = (pInfo)casinoSpecific;

	if (tracker && info)
	{
		tracker->lock();
		tracker->addBadPacket(GAMEID, MACHID, sBadPacketMessages[error_reason].message, sBadPacketMessages[error_reason].severity, info->pid, MessageType, (uint8*)msgbuf, msglen);
		tracker->unlock();
	}
}

int32
RedDogConnection::trackValidateLogin()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = RedDogSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
        tracker->unlock();
    }

    return result;
}

int32
RedDogConnection::trackValidateSession()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = RedDogSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateSession(info->pid, info->sessionId);
        tracker->unlock();
    }

    return result;
}

void RedDogConnection::trackLogoutSession()
{
    pInfo info = (pInfo)casinoSpecific;

	if (tracker && info && !info->login.isEmpty())
    {
        tracker->lock();
		tracker->logout(ServerOpts::casinoId, info->login, info->forMoney, String::emptyString, info->sessionId);
        tracker->unlock();
    }
}

#else	// USE_SQL

#include <string.h>

#include "lib.h"
#include "rdserv.h"
#include "rdconn.h"
#include "rdver.h"
#include "stdncerr.h"
#include "rdgame.h"
#include "rdsaved.h"
#include "shue.h"

#define APP1		(uint8)'R'
#define APP2		(uint8)'D'

typedef struct _info
{
	int32 balance;
} Info, *pInfo;

void RedDogServer::startTracker() { }
void RedDogServer::stopTracker() { }
bool8 RedDogServer::initSuccess() { return Server::initSuccess(); }
void RedDogConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen) {}

bool8
RedDogConnection::parseCasinoLogin(int32 /*stdReq*/, int32* Err)
{
	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		return false;
	}

	Info* info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	info->balance = 100000;		// $1000.00 to start with

	casinoSpecific = info;

	return true;
}
void
RedDogConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
RedDogConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
RedDogConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
RedDogConnection::trackGetBalance()
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
		return info->balance;
	else
		return 0;
}

int32
RedDogConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
	{
		info->balance += Amount;

		return info->balance;
	}
	else
		return 0;
}

bool8
RedDogConnection::trackGetPlayerLimits(int32* minBet, int32* maxBet)
{
	*minBet = 500;
	*maxBet = 50000;

	return true;
}

bool8
RedDogConnection::trackNewGame(int32 Bet, int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;

	if (info)
		*Balance = trackAdjustBalance(-Bet);
	else
		*Balance = 0;

	return true;
}

bool8
RedDogConnection::trackDeal(RedDogHand* /*Player*/, bool8 /*thirdCard*/)
{
	return true;
}

bool8
RedDogConnection::trackGameDone(int32 outcome, int32 BalAdjust,
		int32 *Balance, bool8 raised)
{
	pInfo info = (pInfo)casinoSpecific;

	if (info)
		*Balance = trackAdjustBalance(BalAdjust);
	else
		*Balance = 0;

	return true;
}

bool8
RedDogConnection::trackHasSavedGame(int32* err)
{
	return false;
	RedDogSavedGame sg;

	sg.bet= 500;
	sg.playerCards[0] = 0x1d;
	sg.playerCards[1] = 0x1e;
	sg.shue.next = 0x18;
	sg.shue.seed = 1;

	game = new RedDogGame(this, &sg);
	if (game)
	{
		return true;
	}

	*err = LOGINERR_CONTACTCUSTSERVICE;
	return false;
}

bool8 RedDogConnection::trackSaveGame() { return true; }

#endif
